package cn.com.utt.unms.controller;

import java.io.PrintWriter;
import java.security.Principal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import cn.com.utt.common.alipay.util.AlipayNotify;
import cn.com.utt.common.vo.RestResult;
import cn.com.utt.common.vo.TableInput;
import cn.com.utt.common.vo.TableOutput;
import cn.com.utt.common.vo.User;
import cn.com.utt.unms.pojo.Product;
import cn.com.utt.unms.service.OrderService;
import cn.com.utt.unms.service.SmsBuyService;
import cn.com.utt.unms.vo.OrderItem;

@RestController
@RequestMapping("v1/smsBuy")
public class SmsBuyController {

	@Autowired
	private SmsBuyService smsBuyService;

	@Autowired
	private OrderService orderService;

	@RequestMapping(value = "/product/{id}", method = { RequestMethod.GET })
	public Map<String, Object> info(@PathVariable Long id) {

		RestResult result = new RestResult();

		if (id != null) {
			Product product = smsBuyService.getProduct(id);
			result.put("product", product);
		}

		return result.toJsonObject();
	}

	@RequestMapping(value = "/volume", method = { RequestMethod.GET })
	public Map<String, Object> volume(Principal principal) {

		Authentication authentication = (Authentication) principal;
		User user = (User) authentication.getPrincipal();

		RestResult result = new RestResult();

		long authSmsLef = smsBuyService
				.countAuthSmsByUserId(user.getParentId() == 0 ? user.getId() : user.getParentId());
		long markSmsLef = user.getSmsVolume();

		result.put("authSmsLef", authSmsLef);
		result.put("markSmsLef", markSmsLef);
		return result.toJsonObject();
	}

	@RequestMapping(value = "/buy", method = { RequestMethod.POST })
	public Map<String, Object> buy(Long productId, Integer num, Principal principal) {

		Authentication authentication = (Authentication) principal;
		User user = (User) authentication.getPrincipal();

		String orderNo = orderService.createSmsOrder(user.getParentId() == 0 ? user.getId() : user.getParentId(),
				productId, num);
		 RestResult result = new RestResult();
		 result.put("orderNo", orderNo);
		 return result.toJsonObject();
	}

	@RequestMapping(value = "/payOrder", method = { RequestMethod.GET })
	public void payOrder(HttpServletResponse response, String orderNo) {

		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
			String request = orderService.payOrder(orderNo);
			System.out.println(request);
			if (request != null) {
				out.print(request);
			} else {
				out.print("抱歉，支付失败！");
			}
			out.flush();
		} catch (Exception e) {
			out.print("抱歉，支付失败！");
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}

	@RequestMapping(value = "/payNotify", method = { RequestMethod.POST })
	public void payNotify(HttpServletRequest request, HttpServletResponse response) {

		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
			// 获取支付宝GET过来反馈信息
			Map<String, String> params = new HashMap<String, String>();
			Map<String, String[]> requestParams = request.getParameterMap();
			for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
				String name = (String) iter.next();
				String[] values = (String[]) requestParams.get(name);
				String valueStr = "";
				for (int i = 0; i < values.length; i++) {
					valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
				}
				// 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
				// valueStr = new String(valueStr.getBytes("ISO-8859-1"),
				// "utf-8");
				params.put(name, valueStr);
			}
			// 获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
			// 商户订单号
			String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
			// 支付宝交易号
			String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
			// 交易状态
			String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
			String buyer_email = new String(request.getParameter("buyer_email").getBytes("ISO-8859-1"), "UTF-8");
			// 获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//

			// 计算得出通知验证结果
			boolean verify_result = AlipayNotify.verify(params);

			if (verify_result) {// 验证成功
				if (trade_status.equals("TRADE_FINISHED") || trade_status.equals("TRADE_SUCCESS")) {
					// 判断该笔订单是否在商户网站中已经做过处理
					// 如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
					// 如果有做过处理，不执行商户的业务程序
					orderService.dealOrder(out_trade_no, trade_no, buyer_email);

				}
				out.println("success");
			} else {
				out.println("fail");
			}
		} catch (Exception e) {
			if (out != null) {
				out.println("fail");
			}
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}

	@RequestMapping(value = "/payReturn", method = { RequestMethod.GET })
	public void payReturn(HttpServletRequest request, HttpServletResponse response) {

		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
			// 获取支付宝GET过来反馈信息
			Map<String, String> params = new HashMap<String, String>();
			Map<String, String[]> requestParams = request.getParameterMap();
			for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
				String name = (String) iter.next();
				String[] values = (String[]) requestParams.get(name);
				String valueStr = "";
				for (int i = 0; i < values.length; i++) {
					valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
				}
				// 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
				// valueStr = new String(valueStr.getBytes("ISO-8859-1"),
				// "utf-8");
				params.put(name, valueStr);
			}
			// 获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
			// 商户订单号
			String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
			// 支付宝交易号
			String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
			// 交易状态
			String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
			String buyer_email = new String(request.getParameter("buyer_email").getBytes("ISO-8859-1"), "UTF-8");
			// 获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//

			// 计算得出通知验证结果
			boolean verify_result = AlipayNotify.verify(params);
			System.out.println(verify_result);
			if (verify_result) {// 验证成功
				if (trade_status.equals("TRADE_FINISHED") || trade_status.equals("TRADE_SUCCESS")) {
					// 判断该笔订单是否在商户网站中已经做过处理
					// 如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
					// 如果有做过处理，不执行商户的业务程序
					orderService.dealOrder(out_trade_no, trade_no, buyer_email);
					out.println("支付成功<br />");
				} else {
					out.println("支付出错<br />");
				}
			} else {
				out.println("支付失败<br />");
			}
		} catch (Exception e) {
			e.printStackTrace();
			if (out != null) {
				out.println("支付失败<br />");
			}
		} finally {
			if (out != null) {
				out.flush();
				out.close();
			}
		}
	}

	@RequestMapping(value = "/orders", method = RequestMethod.POST, consumes = "application/json")
	@ResponseBody
	public Map<String, Object> list(@RequestBody TableInput input, Principal principal) {

		Authentication authentication = (Authentication) principal;
		User user = (User) authentication.getPrincipal();

		RestResult result = new RestResult();
		TableOutput<OrderItem> output = orderService.queryByCondition(input,
				user.getParentId() == 0 ? user.getId() : user.getParentId());
		result.put("start", output.getStart());
		result.put("rows", output.getRows());
		result.put("total", output.getTotal());
		result.put("orders", output.getList());
		return result.toJsonObject();
	}

}